package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.client.ArticleFeign;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.AuthorDto;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.mapper.ApUserAuthMapper;
import com.heima.user.service.IApUserAuthService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import com.heima.wemedia.client.WemediaFeign;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-03-13
 */
@Service
public class ApUserAuthServiceImpl extends ServiceImpl<ApUserAuthMapper, ApUserAuth> implements IApUserAuthService {

    @Autowired
    private WemediaFeign wemediaFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserService apUserService;

    @Override
    public PageResult<UserAuthDto> findByPage(AuthDto dto) {
        //构建分页条件
        Page<ApUserAuth> page = new Page<>(dto.getPage(),dto.getSize());
        QueryWrapper<ApUserAuth> queryWrapper = new QueryWrapper<>();
        //构建认证状态查询条件
        if(dto.getStatus()!=null){
            queryWrapper.lambda().eq(ApUserAuth::getStatus,dto.getStatus());
        }
        //执行查询
        IPage<ApUserAuth> iPage = this.page(page, queryWrapper);
        //封装查询结果
        if(CollectionUtils.isEmpty(iPage.getRecords())){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"用户认证列表数据不存在");
        }
        List<UserAuthDto> userAuthDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), UserAuthDto.class);

        return new PageResult<>(dto.getPage(),dto.getSize(),iPage.getTotal(),userAuthDtoList);
    }

    @Override
    //@Transactional
    @GlobalTransactional  // 开启分布式事务管理
    public void updateAuthStatus(AuthDto dto, Integer status) {
        Integer authId = dto.getId();
        //1、更新用户认证状态
        ApUserAuth apUserAuth = new ApUserAuth();
        apUserAuth.setId(authId);
        apUserAuth.setStatus(status);
        apUserAuth.setReason(dto.getMsg());
        //执行更新操作
        boolean b = this.updateById(apUserAuth);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新认证状态失败");
        }
        //2、如果认证状态是未通过，直接返回
        if(ApUserAuth.Status.FAIL.getCode()==status){
            return;
        }
        //3、认证通过
        //查询用户认证数据
        ApUserAuth userAuth = getById(authId);
        //查询app用户数据
        ApUser apUser = apUserService.getById(userAuth.getUserId());
        //3.1 调用自媒体微服务，创建自媒体用户
        WmUserDto wmUserDto = new WmUserDto();
        wmUserDto.setApUserId(userAuth.getUserId());
        wmUserDto.setName(apUser.getName());
        wmUserDto.setPassword(apUser.getPassword());
        wmUserDto.setImage(apUser.getImage());
        wmUserDto.setPhone(apUser.getPhone());
        wmUserDto.setStatus(9);//正常可用状态
        wmUserDto.setType(0);//个人账户
        Integer wmUserId = wemediaFeign.saveWmUser(wmUserDto);
        //3.2 调用文章微服务，创建作者信息
        AuthorDto authorDto = new AuthorDto();
        authorDto.setName(apUser.getName());
        authorDto.setUserId(apUser.getId());
        authorDto.setWmUserId(wmUserId);
        authorDto.setType(2);//平台自媒体人
        Integer authorId = articleFeign.saveAuthor(authorDto);
        //3.3 修改app用户的flag标志，由普通用户改为自媒体标志
        apUser = new ApUser();
        apUser.setFlag(1);//自媒体用户
        apUser.setId(userAuth.getUserId());
        boolean b1 = apUserService.updateById(apUser);
        if(!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更正App用户类型失败");
        }
        //int i=1/0;
    }
}
